import os
import re

def extract_number(filename):
    """从文件名中提取数字序号，忽略后缀"""
    # 移除所有非数字字符，只保留最后的连续数字
    numbers = re.findall(r'\d+', filename)
    return numbers[-1] if numbers else None

def find_matching_file(target_num, file_list):
    """在文件列表中查找序号匹配的文件"""
    for f in file_list:
        if extract_number(f) == target_num:
            return f
    return None

def get_Results(output_dir, input_dir, ans_dir, shuchu_dir, an):
    os.makedirs(shuchu_dir, exist_ok=True)
    
    summary_path = os.path.join(shuchu_dir, f"{an}-result.txt")
    with open(summary_path, 'w') as summary_file:
        summary_file.write(f"Starting tests {an} output...\n")
        
        # 预处理目录文件列表
        ans_files = os.listdir(ans_dir)
        input_files = os.listdir(input_dir)
        output_files = os.listdir(output_dir)
        
        for output_file in output_files:
            if not output_file.endswith(".txt"):
                continue
                
            # 提取output文件的序号
            output_num = extract_number(output_file)
            if not output_num:
                print(f"警告: 无法从文件名提取序号: {output_file}")
                continue
            
            # 在ans目录查找对应文件（忽略后缀）
            ans_file = find_matching_file(output_num, ans_files)
            if not ans_file:
                print(f"警告: 未找到ans目录中与{output_file}对应的文件")
                continue
                
            # 提取来源信息
            source_parts = ans_file.split('-')
            source = source_parts[-2] if len(source_parts) >= 2 else "unknown"
            
            # 在input目录查找对应文件（忽略后缀）
            input_file = find_matching_file(output_num, input_files)
            N, C = "0", "0"
            if input_file:
                try:
                    with open(os.path.join(input_dir, input_file), 'r') as f:
                        first_line = f.readline().strip()
                        parts = first_line.split()
                        if len(parts) >= 2:
                            N, C = parts[0], parts[1]
                except Exception as e:
                    print(f"警告: 读取input文件{input_file}失败: {str(e)}")
            
            # 构建输出文件名
            output_filename = f"{an}-{source}-{output_num}-N{N}-C{C}.txt"
            output_path = os.path.join(shuchu_dir, output_filename)
            
            # 读取output文件内容
            with open(os.path.join(output_dir, output_file), 'r') as f:
                output_content = f.read().strip()
            
            # 处理特殊情况和结果判断
            if "Timeout" in output_content:
                result = "Timeout"
                with open(output_path, 'w') as f:
                    f.write("Timeout")
                summary_line = f"{an}-{source}-{output_num}: Timeout"
                    
            elif "Alloc fail" in output_content:
                result = "Alloc fail"
                with open(output_path, 'w') as f:
                    f.write("Alloc fail")
                summary_line = f"{an}-{source}-{output_num}: Alloc fail"
                
            else:
                # 读取ans文件第一行
                with open(os.path.join(ans_dir, ans_file), 'r') as f:
                    ans_first_line = f.readline().strip()
                
                # 比较结果
                output_first_line = output_content.split('\n')[0].strip()
                if output_first_line == ans_first_line:
                    result = "Correct"
                    with open(output_path, 'w') as f:
                        f.write("Correct\n")
                        f.write(output_content)
                else:
                    result = "Wrong"
                    with open(output_path, 'w') as f:
                        f.write("Wrong\n")
                        f.write(output_content)
                
                # 提取时间信息
                time_match = re.search(r"(\d+\.\d+)ms", output_content)
                time_str = time_match.group(0) if time_match else "0.000000ms"
                summary_line = f"{an}-{source}-{output_num}: {result} - {time_str}"
            
            summary_file.write(summary_line + "\n")
        
        summary_file.write("All tests completed.\n")



# 示例使用
if __name__ == "__main__":
    # 设置路径参数
    algorithm_name = "dp" 
    output_dir = "../output/"+ algorithm_name + "/"
    input_dir = "../../data/input/" 
    ans_dir = "../../data/ans/"
    shuchu_dir = "../result/"+ algorithm_name + "/"
    
    
    get_Results(output_dir, input_dir, ans_dir, shuchu_dir, algorithm_name)